package com.XDApp.xdbase.activitys;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.XDApp.xdbase.BaseActivity;
import com.XDApp.xdbase.BaseApplication;
import com.XDApp.xdbase.XDHttpClient;
import com.XDApp.xdbase.bean.User;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.ProgressHUD;
import com.XDApp.xdbase.utils.UpdateUserState;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.view.CRToast;
import com.XDApp.xdbase.xinsilu.R;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class LoginActivity extends BaseActivity implements OnClickListener {
	private final String TAG = "LoginActivity";
	private ImageView iv_back;
	private TextView tv_title, tv_right;
	private Button bt_login;
	private EditText et_username, et_pwd;
	private String username, pwd;
	private SharedPreferences sp;
	private BaseApplication application;

	@Override
	protected void initViews() {
		setContentView(R.layout.activity_login);
		application = BaseApplication.getApplication();
		sp = getSharedPreferences(MainActivity.class.getSimpleName(), MODE_PRIVATE);

		iv_back = (ImageView) findViewById(R.id.title_back);
		tv_title = (TextView) findViewById(R.id.title_text);
		tv_right = (TextView) findViewById(R.id.title_right);
		bt_login = (Button) findViewById(R.id.bt_login);
		et_username = (EditText) findViewById(R.id.username);
		et_pwd = (EditText) findViewById(R.id.pwd);

		findViewById(R.id.tv_forgetpwd).setOnClickListener(this);

	}

	@Override
	protected void initEvents() {
		bt_login.setOnClickListener(this);
		tv_right.setOnClickListener(this);
		bt_login.setClickable(false);
		iv_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		tv_title.setText("登录");
		tv_right.setText("注册");
		tv_right.setTextColor(Color.WHITE);

		et_username.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				bt_login.setBackgroundResource(R.drawable.bt_login_normal);
				bt_login.setTextColor(Color.parseColor("#777777"));
				bt_login.setClickable(false);
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (TextUtils.isEmpty(et_pwd.getText().toString().trim())) {
					return;
				}
				if (TextUtils.isEmpty(et_username.getText().toString().trim())) {
					bt_login.setBackgroundResource(R.drawable.bt_login_normal);
					bt_login.setTextColor(Color.parseColor("#777777"));
					bt_login.setClickable(false);
					return;
				}
				bt_login.setBackgroundResource(R.drawable.bt_login_press);
				bt_login.setTextColor(Color.WHITE);
				bt_login.setClickable(true);
			}
		});

		et_pwd.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence text, int arg1, int arg2, int arg3) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				bt_login.setBackgroundResource(R.drawable.bt_login_normal);
				bt_login.setTextColor(Color.parseColor("#777777"));
				bt_login.setClickable(false);
			}

			@Override
			public void afterTextChanged(Editable arg0) {
				if (TextUtils.isEmpty(et_username.getText().toString().trim())) {
					return;
				}
				if (TextUtils.isEmpty(et_pwd.getText().toString().trim())) {
					bt_login.setBackgroundResource(R.drawable.bt_login_normal);
					bt_login.setTextColor(Color.parseColor("#777777"));
					bt_login.setClickable(false);
					return;
				}
				bt_login.setBackgroundResource(R.drawable.bt_login_press);
				bt_login.setTextColor(Color.WHITE);
				bt_login.setClickable(true);
			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_login:// 登录
			username = et_username.getText().toString();
			pwd = et_pwd.getText().toString();
			getData(username, pwd);
			break;
		case R.id.title_right:// 注册
			Intent intent = new Intent(LoginActivity.this, RegistFirstActivity.class);
			startActivity(intent);
			break;
		case R.id.tv_forgetpwd:
			Intent intent2 = new Intent(LoginActivity.this, RegistFirstActivity.class);
			intent2.putExtra(RegistFirstActivity.PARAM_IS_REGISTER, false);
			startActivity(intent2);
			break;
		default:
			break;
		}
	}

	// TODO 访问网络获取数据
	private void getData(final String name, final String pwd) {
		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("userName", name);
			params.put("password", md5(pwd));
			params.put("ostype", xdConfig.ANDRODID);

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.LOGIN, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					Log.e(TAG, content);
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();

					new JSONObject();
					JSONObject obj = JSONObject.parseObject(content);
					String data1 = obj.getString("data");
					String state = obj.getString("state");
					if ("1".equals(state)) {// {"nickName":"13521870239","userID":"187","userLogo":""}
						CRToast.show(LoginActivity.this, "登录成功");
						User user = JSON.parseObject(data1, User.class);
						Editor editor = sp.edit();
						editor.putString("phone", user.getMobile()).commit();
						editor.putString("email", user.getEmail()).commit();
						editor.putString("pwd", pwd).commit();
						editor.putString("userID", user.getUserID()).commit();
						editor.putString("nickName", user.getNickName()).commit();
						editor.putString("userLogo", user.getUserLogo()).commit();
						application.setLogin(true);
						application.setUser(user);
						Intent data = new Intent();
						data.putExtra("loginSuccess", true);
						data.putExtra("nickName", user.getNickName());
						data.putExtra("pwd", user.getPwd());
						data.putExtra("userID", user.getUserID());
						data.putExtra("userLogo", user.getUserLogo());
						data.putExtra("phone", user.getMobile());
						data.putExtra("email", user.getEmail());
						setResult(110, data);
						UpdateUserState.notifyUpdateUser(data);
						finish();
					} else {
						Intent data = new Intent();
						data.putExtra("loginSuccess", false);
						setResult(110, data);
						application.setLogin(false);
						CRToast.show(LoginActivity.this, "帐号或者密码错误");
						return;
					}
				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}

	public static String md5(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

}
